package com.dlx.serurity.filter;

import com.dlx.common.result.R;
import com.dlx.common.utils.ResponseUtil;
import com.dlx.serurity.entity.SecurityUser;
import com.dlx.serurity.entity.SmsCodeAuthenticationToken;
import com.dlx.serurity.entity.User;
import com.dlx.serurity.provider.SmsCodeAuthenticationProvider;
import com.dlx.serurity.security.TokenManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Objects;

/**
 * <p>
 * 登录过滤器，继承UsernamePasswordAuthenticationFilter，对用户名密码进行登录校验
 * </p>
 *
 * @author qy
 * @since 2019-11-08
 */
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {

    private SmsCodeAuthenticationProvider smsCodeAuthenticationProvider;
    private AuthenticationManager authenticationManager;
    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;

    public TokenLoginFilter(SmsCodeAuthenticationProvider smsCodeAuthenticationProvider, AuthenticationManager authenticationManager, TokenManager tokenManager, RedisTemplate redisTemplate) {
        this.smsCodeAuthenticationProvider = smsCodeAuthenticationProvider;
        this.authenticationManager = authenticationManager;
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
        this.setPostOnly(false);
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/admin/acl/login", "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException {
        try {
            User user = new ObjectMapper().readValue(req.getInputStream(), User.class);
            if (StringUtils.hasText(user.getMobile())) {
                SmsCodeAuthenticationToken smsCodeAuthenticationToken = new SmsCodeAuthenticationToken(user.getMobile());
                this.setDetails(user.getCaptcha(), smsCodeAuthenticationToken);
                return smsCodeAuthenticationProvider.authenticate(smsCodeAuthenticationToken);
            } else {
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(Objects.nonNull(user.getUsername()) ? user.getUsername() : user.getEmail(), user.getPassword(), new ArrayList<>());
                return authenticationManager.authenticate(usernamePasswordAuthenticationToken);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 登录成功
     *
     * @param req
     * @param res
     * @param chain
     * @param auth
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
                                            Authentication auth) throws IOException, ServletException {
        SecurityUser user = (SecurityUser) auth.getPrincipal();
        String token = null;
        if (StringUtils.hasText(user.getCurrentUserInfo().getUsername())) {
            token = tokenManager.createToken(user.getCurrentUserInfo().getUsername());
        } else if (StringUtils.hasText(user.getCurrentUserInfo().getEmail())) {
            token = tokenManager.createToken(user.getCurrentUserInfo().getEmail());
        } else if (StringUtils.hasText(user.getCurrentUserInfo().getMobile())) {
            token = tokenManager.createToken(user.getCurrentUserInfo().getMobile());
        }
        String permissionValueListKey = null;
        if (StringUtils.hasText(user.getCurrentUserInfo().getUsername())) {
            permissionValueListKey = user.getCurrentUserInfo().getUsername();
        } else if (StringUtils.hasText(user.getCurrentUserInfo().getEmail())) {
            permissionValueListKey = user.getCurrentUserInfo().getEmail();
        } else if (StringUtils.hasText(user.getCurrentUserInfo().getMobile())) {
            permissionValueListKey = user.getCurrentUserInfo().getMobile();
        }
        assert permissionValueListKey != null;
        redisTemplate.opsForValue().set(permissionValueListKey, user.getPermissionValueList());

        ResponseUtil.out(res, R.ok().data("token", token));
    }

    /**
     * 登录失败
     *
     * @param request
     * @param response
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                              AuthenticationException e) throws IOException, ServletException {
        ResponseUtil.out(response, R.error());
    }

    protected void setDetails(String captcha, SmsCodeAuthenticationToken authRequest) {
        authRequest.setDetails(captcha);
    }
}
